package com.magicodex.bookkeeping.biz.common.util;

import android.content.Context;

import com.magicodex.bookkeeping.biz.common.exception.ApplicationException;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

/**
 * @author mh.z
 */
public class FileUtil {

    /**
     * 从内部存储文件读取数据
     *
     * @param context
     * @param path
     * @return
     */
    public static String readFile(Context context, String path) {
        CheckUtil.notNull(context, "context null");
        CheckUtil.notNull(path, "path null");
        String content = null;

        try (FileInputStream inputStream = context.openFileInput(path)) {
            content = getString(inputStream);
        } catch (FileNotFoundException e) {
            //
        } catch (IOException e) {
            throw new ApplicationException(e);
        }

        return content;
    }

    /**
     * 写入数据到内部存储文件
     *
     * @param context
     * @param path
     * @param content
     */
    public static void writeFile(Context context, String path, String content) {
        CheckUtil.notNull(context, "context null");
        CheckUtil.notNull(path, "path null");

        try (FileOutputStream outputStream = context.openFileOutput(path, Context.MODE_PRIVATE)) {
            byte[] bytes = null;

            if (StringUtil.isNotEmpty(content)) {
                bytes = content.getBytes(StandardCharsets.UTF_8);
            } else {
                bytes = new byte[0];
            }

            outputStream.write(bytes);
        } catch (IOException e) {
            throw new ApplicationException(e);
        }
    }


    /**
     * 读取输入流的数据并返回
     *
     * @param inputStream
     * @return
     */
    public static String getString(InputStream inputStream) {
        CheckUtil.notNull(inputStream, "inputStream null");

        try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
            byte[] buffer = new byte[1024];
            int length = -1;

            while ((length = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, length);
            }

            byte[] bytes = outputStream.toByteArray();
            String content = new String(bytes, StandardCharsets.UTF_8);

            return content;
        } catch (IOException e) {
            throw new ApplicationException(e);
        }
    }

}
